package xiaoyou.service;

import java.sql.Connection;
import java.util.List;

import org.apache.commons.dbutils.DbUtils;
import org.apache.log4j.Logger;

import xiaoyou.dao.UserDao;
import xiaoyou.entity.User;
import xiaoyou.neoutil.CommonService;
import xiaoyou.neoutil.DaoSupport;
import xiaoyou.neoutil.Page;
import xiaoyou.neoutil.StringEncrypt;

public class UserRepository extends CommonService {
	private static Logger log = Logger.getLogger(UserRepository.class);
	private String SQL_INSERT = "INSERT INTO user(name, email, password, role, entityStatus) VALUES(?, ?, ?, ?, ?)";
	private String SQL_UPDATE = "UPDATE user SET name=?, email=?, password=?, role=?, entityStatus=? WHERE id=?";
	private String SQL_DELETE_BY_ID = "UPDATE user SET entityStatus=0 WHERE id=?";
	private String SQL_GET_BY_ID = "SELECT * FROM user WHERE id=? AND entityStatus=1";
	private String SQL_GET_ALL = "SELECT * FROM user";
	private String SQL_LOGIN = "SELECT * FROM user WHERE email=? AND password=?";

	public int save(User user) {
		Connection connection = DaoSupport.getConnection();
		UserDao userDao = new UserDao(connection);

		try {
			Object[] params = { user.getName(), user.getEmail(),
					user.getPassword(), user.getRole(), user.getEntityStatus() };
			userDao.execute(SQL_INSERT, params);
			return SUCCESS;
		} catch (Exception e) {
			log.error("保存User对象出现异常！！");
			e.printStackTrace();
			return FAIL;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public int update(User user) {
		Connection connection = DaoSupport.getConnection();
		UserDao userDao = new UserDao(connection);

		try {
			Object[] params = { user.getName(), user.getEmail(),
					user.getPassword(), user.getRole(), user.getEntityStatus(),
					user.getId() };
			userDao.execute(SQL_UPDATE, params);
			return SUCCESS;
		} catch (Exception e) {
			log.error("更新User对象出现异常！！");
			e.printStackTrace();
			return FAIL;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public int delete(User user) {
		Connection connection = DaoSupport.getConnection();
		UserDao userDao = new UserDao(connection);

		try {
			Object[] params = { user.getId() };
			userDao.execute(SQL_DELETE_BY_ID, params);
			return SUCCESS;
		} catch (Exception e) {
			log.error("假删除User对象出现异常！！");
			e.printStackTrace();
			return FAIL;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public User get(long id) {
		Connection connection = DaoSupport.getConnection();
		UserDao userDao = new UserDao(connection);

		try {
			Object[] params = { id };
			List<User> users = userDao.find(SQL_GET_BY_ID, params);
			if (users == null) {
				return null;
			} else if (users.size() > 1) {
				log.error("根据ID查询到的User个数不唯一，为防止错误，返回null!");
				return null;
			} else {
				return users.get(0);
			}
		} catch (Exception e) {
			log.error("根据ID取得User对象出现异常！！");
			e.printStackTrace();
			return null;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public Page<User> getUsers(final Page<User> page) {
		Connection connection = DaoSupport.getConnection();
		UserDao userDao = new UserDao(connection);

		try {
			Page<User> users = userDao.find(page, SQL_GET_ALL);
			return users;
		} catch (Exception e) {
			log.error("取得所有User对象出现异常！！");
			e.printStackTrace();
			return null;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public User login(String email, String password) {
		Connection connection = DaoSupport.getConnection();
		UserDao userDao = new UserDao(connection);

		try {
			Object[] params = { email, StringEncrypt.encrypt(password) };
			List<User> users = userDao.find(SQL_LOGIN, params);
			if (users == null) {
				return null;
			} else if (users.size() > 1) {
				log.error("该Email和密码对应的用户不唯一，为防止错误，返回null!");
				return null;
			} else {
				return users.get(0);
			}
		} catch (Exception e) {
			log.error("根据ID取得User对象出现异常！！");
			e.printStackTrace();
			return null;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	/**
	 * Description:
	 * 
	 * @param args
	 *            void
	 */
	public static void main(String[] args) {
		User user = new User();
		user.setName("admin");
		user.setEmail("cyp_bkd@qq.com");
		user.setPassword("1");
		user.setRole(User.ADMINISTRATOR);
		user.setId(1L);

		UserRepository userRepository = new UserRepository();
		userRepository.save(user);
		// userRepository.update(user);
		// User user;
		// user = userRepository.login("test@xiaoyou.com", "test");
		// System.out.println(user.getEmail());
	}
}
